<template>
  <view class="page">
    <!-- 公共组件-每个页面必须引入 -->
    <public-module></public-module>


	<view class="u-padding-20">
		
		<u--form labelPosition="left" labelWidth="40" >
			<u-form-item label="分类">

				  <u-radio-group v-model="category_id" placement="row" @change="radioGroupChange">
					<u-grid col="2" align="left" :border="false" style="width: 100%;">
							<u-grid-item v-for="(cate, index) in bbscate">
								<u-radio
									:label="cate.category_name"
									:key="index"
									:labelSize="16" :size="16"
									:customStyle="{marginTop: '15px'}"
									:name="cate.category_id">
								</u-radio>
							</u-grid-item>
					</u-grid>
				  </u-radio-group>

			</u-form-item>
			
			<u-form-item label="检查"  @click="$tools.goJump('/pages/user/useredit',{},!userInfo.token,'')" v-if="canfabu==false">
				<span class="u-error-dark">{{canfabu_txt}}</span>
			</u-form-item>
			
			<u-form-item label="标题">
					<u--input placeholderStyle="font-size:14px" v-model="info.title" placeholder="标题(可留空)" type="text"/>
			</u-form-item>
			
			
			<u-form-item label="内容">
				<editor id="editor" class="editor-container" placeholder="请输入内容" @input="getEditorContent" @ready="onEditorReady"></editor>
			</u-form-item>

			
			<u-form-item label="图片" :borderBottom="false">
					<u-upload 
						:fileList="fileList2"
						@afterRead="afterRead"
						maxCount="5"
						@delete="deletePic"
						name="2"
						width="60"
						height="60">
					</u-upload>
			</u-form-item>

		</u--form>

			<u-button type="primary" @click="submit()" :disabled="!canfabu">
				<span v-if="canfabu">投稿</span>
				<span v-else>发布前请先完善：{{canfabu_txt}}</span>
			</u-button>
		</view>
		
		
		<view class="u-p-l-20 u-p-r-20 u-p-b-20">
		<u-alert :title="'友情提示：'" type = "error" :description = "'非【达人】用户投稿提交后，请耐心等待审核，审核通过后方可对外展示。在未审核前，仅允许投稿者本人查看和修改内容。'"></u-alert>
		</view><u-gap height="8" bg-color="#f3f4f6"></u-gap>
		<u-gap height="20"></u-gap>
	<u-tabbar
		value="0"
		:fixed="true"
		:border="true"
		:placeholder="true"
		:safeAreaInsetBottom="true">  
		<u-tabbar-item text="首页" icon="home" @click="tabbarswitch" ></u-tabbar-item>
		<u-tabbar-item text="我的信息" icon="list" @click="tabbarswitch" ></u-tabbar-item>
	</u-tabbar>
  </view>
  </view>
</template>


<script>
import { mapState, mapMutations } from "vuex";
import base from "@/config/baseUrl";
import { uploadFilePromise } from '@/plugins/upload/upload';
import {api_info_save,api_content_info } from '@/config/api.js';
import { loGetLocation } from '@/config/common';
export default {
  data() {
    return {
      fileList1:[],
	  fileList2:[],
	  fileList3:[],
	  info:{
		  content:'',
		  name:''
	  },
      paystatus:false,
      loadstxt: "loading...",
	  bbscate:[],
	  info:[],
	  category_id: '',
	  content_id:'',
	  canfabu:true,
	  canfabu_txt:'',
	  currlocation:[]
    };
  },
  computed: {
    ...mapState(["userInfo"]),
  },
  watch: {

  },
   onLoad(options) {
		this.content_id = options.content_id;
		if(this.content_id>0){
			this.getpagecontrac(this.content_id);
		}
		let siteinfo = uni.getStorageSync('siteInfo');
		this.bbscate=siteinfo.bbscate
		
		// #ifdef MP-WEIXIN
            loGetLocation(res=>{
				console.log('loGetLocation',res)
				this.currlocation=res
            },err=>{},true) 	
		// #endif
		
		this.checkcanfabu()
  },

  methods: {
	  checkcanfabu(){
		this.$store.dispatch("getUserInfo",{member_id:this.userInfo.member_id}).then(rs=>{
		  if(rs.avatar_id==0){
			  this.canfabu=false
			  this.canfabu_txt=this.canfabu_txt+' [上传头像] '
		  }
		  if((rs.nickname==''||rs.nickname==null)&&(rs.realname==''||rs.realname==null)){
			  this.canfabu=false
			  this.canfabu_txt=this.canfabu_txt+' [昵称或名字] '
		  }
		  
		  if(rs.phone==''||rs.phone==null){
			  this.canfabu=false
			  this.canfabu_txt=this.canfabu_txt+' [手机] '
		  }
		});
	  },
	  	tabbarswitch(index) {
	  		if (index==1){
				this.judgeLogin(() => {
					this.$tools.goJump('/pagesPackageA/info/myfabu',{entertabid:0},'','')
				})
			}
	  		if (index==0){
				this.$tools.goJump('/pages/my/myInfo',{},'','launch')
			}
	  	},
        onEditorReady() {/////////////////////////初始化
                uni.createSelectorQuery().select('#editor').context((res) => {
                    var contentVal_1 = this.info.content;
                    //将内容写入编辑器
                    this.editorCtx = res.context;
                    let EContent = {
                        html: contentVal_1
                    }
                    this.editorCtx.setContents(EContent); //设置富文本编辑器的内容
                }).exec()
            },
            getEditorContent(e) {/////////////////////////获取编辑器内容，当前页面都能获取到
                this.info.content = e.detail.html;
            },

		radioChange(e) {
			 console.log(e);
		},
		radioGroupChange(e) {
			this.info.category_ids=[e]
			console.log(this.info);
		},
    getpagecontrac(content_id) {
		this.loadstatus = true;
		api_content_info({
				content_id:content_id
			}).then((res) => {
				console.log('getpagecontrac',res)				
					this.info=res
					this.category_id= this.info.category_ids.length > 0 ? this.info.category_ids[0] : '';
					this.onEditorReady()
				res.images.map((item) => {
					this.fileList2.push({
						file_id:item.file_id,
						url:item.file_url
					})
				})
				this.loadstatus = false;
			  }).catch((e) => {});
    },
			
	submit(){
		if(!this.category_id>0){
			this.$tools.msg('请选择一个分类。')
			return;
		}
		
		
		var cover_id = ''
		if (this.fileList1.length>0){
			this.fileList1.map((item) => {
				cover_id=item.file_id
			})
		}
		let images = []
		this.fileList2.map((item) => {
			images.push({
				file_url:item.url,
				file_id:item.file_id
			})
		})
		
		let data={
			...this.info,
			location:JSON.stringify(this.currlocation),
			images_ids:JSON.stringify(images)
		}
		console.log('data',data)
		api_info_save(data).then((res) => {
			this.$tools.msg('保存成功。')
			setTimeout(()=>{
				this.$tools.goJump('/pages/my/myInfo',{},'','launch')
			},500)
		}).catch((e) => {});
	},
	


			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await uploadFilePromise(lists[i].url,2)
					let item = this[`fileList${event.name}`][fileListLen]
					
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						file_id: result.file_id,
						url: result.file_url
					}))
					//this[`fileList${event.name}`][fileListLen].url=result
					fileListLen++
				}
			},

  },
};
</script>
<style lang="scss" scoped>
	.editor-container{
		border: solid 1px #cccccc;
		padding:5px;
		border-radius: 6px;
	}

</style>
